package com.vm.activity;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.vm.commons.CurrentUser;
import com.vm.commons.VMConst;
import com.vm.fragment.UIHelper;
import com.vm.model.ActiveSoft;
import com.vm.myview.ViewUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;

@SuppressLint("HandlerLeak")
public class PresentActivity extends Activity {

	protected static final String TAG = "IndispensabilityActivity";

	private RequestQueue mQueue;
	ImageView imgbtn_back;
	Button btn_search;
	RadioGroup nav_radiogroup;
	RadioButton rbtn_time0;
	RadioButton rbtn_time8;
	RadioButton rbtn_time10;
	RadioButton rbtn_time12;
	RadioButton rbtn_time14;
	RadioButton rbtn_time16;
	RadioButton rbtn_time18;
	RadioButton rbtn_time20;
	RadioButton rbtn_time22;

	ImageView iv_instruction;

	EditText et_appname;

	ScrollView mScrollView;
	boolean canRequest = false;
	int pageNow = 1;
	LinearLayout found_ll_1;
	TextView tv_time2;
	TextView tv_time3;

	TextView tv_hour;
	TextView tv_minutes;
	TextView tv_seconds;

	ViewUtils viewUtils;
	RelativeLayout rlayout_timing;
	int time_zone = 1;
	String serverTime = null;
	int hour = 0;
	int minutes = 0;
	int seconds = 0;

	int hour1 = 0;
	int minutes1 = 0;
	int seconds1 = 0;
	String st_zone = null;
	int progressVisable = 0;

	Timer timer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.present1_nav);

		viewUtils = new ViewUtils(this);
		mQueue = MyVolley.getRequestQueue();
		init();
		getServerTime();
		// doTime();

	}

	public void init() {
		//
		// et_appname = (EditText) findViewById(R.id.et_appname);
		// et_appname.setFocusable(false);
		// rbtn_ongoing = (RadioButton)findViewById(R.id.btn_ongoing);
		// rbtn_will_begin = (RadioButton)findViewById(R.id.btn_will_begin);
		imgbtn_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		// btn_search = (Button) findViewById(R.id.btn_search);
		imgbtn_back.setOnClickListener(btn_backListener);
		// btn_search.setOnClickListener(searchClickListener);

		found_ll_1 = (LinearLayout) findViewById(R.id.found_ll_1);
		rlayout_timing = (RelativeLayout) findViewById(R.id.rlayout_timing);

		mScrollView = (ScrollView) findViewById(R.id.scrollview_list);

		nav_radiogroup = (RadioGroup) findViewById(R.id.nav_radiogroup);
		nav_radiogroup.setOnCheckedChangeListener(group_listener);
		rbtn_time0 = (RadioButton) findViewById(R.id.btn_time0);
		rbtn_time8 = (RadioButton) findViewById(R.id.btn_time8);
		rbtn_time10 = (RadioButton) findViewById(R.id.btn_time10);
		rbtn_time12 = (RadioButton) findViewById(R.id.btn_time12);
		rbtn_time14 = (RadioButton) findViewById(R.id.btn_time14);
		rbtn_time16 = (RadioButton) findViewById(R.id.btn_time16);
		rbtn_time18 = (RadioButton) findViewById(R.id.btn_time18);
		rbtn_time20 = (RadioButton) findViewById(R.id.btn_time20);
		rbtn_time22 = (RadioButton) findViewById(R.id.btn_time22);

		tv_time2 = (TextView) findViewById(R.id.tv_time2);
		tv_time3 = (TextView) findViewById(R.id.tv_time3);

		tv_hour = (TextView) findViewById(R.id.tv_hour);
		tv_minutes = (TextView) findViewById(R.id.tv_minutes);
		tv_seconds = (TextView) findViewById(R.id.tv_seconds);

		iv_instruction = (ImageView) findViewById(R.id.iv_instruction);
		iv_instruction.setOnClickListener(btn_instruction);
		//
		//
		// rbtn_ongoing.setOnClickListener(rbtnClickListener);
		// rbtn_will_begin.setOnClickListener(rbtnClickListener);

	}

	/**
	 * 积分专区介绍
	 */
	OnClickListener btn_instruction = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(PresentActivity.this,
					PresentIntroActivity.class);
			startActivity(intent);
		}
	};

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	public void initData() {

		UIHelper.showDialogForLoading(this, "正在加载数据...", true);
		mScrollView.setVisibility(View.INVISIBLE);
		String url = VMConst.REQUEST_URL
				+ VMConst.ActiveType.getPresent.toString() + "?activeTime="
				+ time_zone;
		if (CurrentUser.USERID != null) {
			url += "&userId=" + CurrentUser.USERID;
		}

		// 重置,否则始终为1
		progressVisable = 0;
		if (hour == time_zone || hour - 1 == time_zone) {
			progressVisable = 1;
		}

		JsonArrayRequest json_present = new JsonArrayRequest(url,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						if (arg0.length() == 10) {
							canRequest = true;
						}

						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								final ActiveSoft activeSoft = JsonUtils
										.jsonToBean(jsonObject,
												ActiveSoft.class);
								if (activeSoft != null) {
									LinearLayout linearLayout = viewUtils
											.dyAddView2(i, activeSoft,
													progressVisable);
									found_ll_1.addView(linearLayout);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						new Thread(new Runnable() {
							@Override
							public void run() {
								spandTimeMethod();// 耗时的方法
								handler1.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
							}

						}).start();
						// UIHelper.hideDialogForLoading();

					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_present);
	}

	/**
	 * 单选按钮监听
	 */
	public OnCheckedChangeListener group_listener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {

			// 默认为0
			int time1 = 0;
			int time2 = 0;

			switch (checkedId) {
			case R.id.btn_time0:
				time_zone = 0;
				if (hour >= 8) {
					time1 = 2;
				}
				st_zone = "00:01-08:00";
				break;
			case R.id.btn_time8:
				time_zone = 8;
				if (hour < 10) {
					if (hour < 8) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}

				st_zone = "08:01-10:00";
				break;
			case R.id.btn_time10:
				time_zone = 10;
				if (hour < 12) {
					if (hour < 10) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}
				st_zone = "10:01-12:00";
				break;
			case R.id.btn_time12:
				time_zone = 12;
				if (hour < 14) {
					if (hour < 12) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}
				st_zone = "12:01-14:00";
				break;
			case R.id.btn_time14:
				time_zone = 14;
				if (hour < 16) {
					if (hour < 14) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}
				st_zone = "14:01-16:00";
				break;
			case R.id.btn_time16:
				time_zone = 16;
				if (hour < 18) {
					if (hour < 16) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}
				st_zone = "16:01-18:00";
				break;
			case R.id.btn_time18:
				time_zone = 18;
				if (hour < 20) {
					if (hour < 18) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}
				st_zone = "18:01-20:00";
				break;
			case R.id.btn_time20:
				time_zone = 20;
				if (hour < 22) {
					if (hour < 20) {
						time1 = 1;
						time2 = 1;
					}
				} else {
					time1 = 2;
				}
				st_zone = "20:01-22:00";
				break;
			case R.id.btn_time22:
				time_zone = 22;
				if (hour < 22) {
					time1 = 1;
					time2 = 1;
				}
				st_zone = "22:01-00:00";
				break;
			}
			setTimeView(time1, time2);

		}
	};

	/**
	 * 设置各时间View的显示
	 */
	public void setTimeView(int time1, int time2) {
		if (time1 == 0) {
			tv_time2.setText("正在进行");
		} else if (time1 == 1) {
			tv_time2.setText("即将开始");
		} else {
			tv_time2.setText("明日时间");
		}

		if (time2 == 0) {
			rlayout_timing.setVisibility(View.INVISIBLE);
		} else {
			rlayout_timing.setVisibility(View.VISIBLE);
		}

		Log.i(TAG, "time_zone:" + time_zone + ",hour:" + hour);
		tv_time3.setText(st_zone);
		found_ll_1.removeAllViews();
		initData();
	}

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();

	}

	/**
	 * 搜索按钮监听
	 */
	public OnClickListener searchClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(PresentActivity.this,
					SearchActivity.class);
			startActivity(intent);
		}
	};

	OnItemClickListener gd_listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(PresentActivity.this,
					DetailActivity.class);
			TextView textView = (TextView) view.findViewById(R.id.tv_softName);
			String softId = textView.getTag().toString();
			intent.putExtra("softId", softId);
			startActivityForResult(intent, 10);

		}
	};

	@SuppressWarnings("unused")
	private class TouchListenerImpl implements OnTouchListener {
		@SuppressLint("ClickableViewAccessibility")
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {

					Log.i(TAG, Boolean.toString(canRequest));
					if (canRequest) {
						canRequest = false;
						System.out.print("canRequest:" + canRequest);
						pageNow += 1;
						System.out.print("pageNow:" + pageNow);
						String url = VMConst.REQUEST_URL
								+ VMConst.ActiveType.getPresent.toString()
								+ "?pageNow=" + pageNow + "&activeTime="
								+ time_zone;
						if (CurrentUser.USERID != null) {
							url += "&userId=" + CurrentUser.USERID;
						}
						JsonArrayRequest presntArrayRequest = new JsonArrayRequest(
								url, new Listener<JSONArray>() {
									@Override
									public void onResponse(JSONArray arg0) {
										Log.i(TAG, "json长度:" + arg0.length());

										for (int i = 0; i < arg0.length(); i++) {
											try {
												JSONObject jsonObject = arg0
														.getJSONObject(i);
												final ActiveSoft activeSoft = JsonUtils
														.jsonToBean(
																jsonObject,
																ActiveSoft.class);
												if (activeSoft != null) {
													LinearLayout linearLayout = viewUtils
															.dyAddView2(i,
																	activeSoft,
																	1);
													found_ll_1
															.addView(linearLayout);
												}
											} catch (JSONException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
										}

										canRequest = true;

									}

								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										// Log.e(TAG, error.getMessage(),
										// error);
									}
								});

						mQueue.add(presntArrayRequest);
					}

				}
				break;

			default:
				break;
			}
			return false;
		}

	};

	/**
	 * 获取服务器当前时间
	 */
	public void getServerTime() {
		String url = VMConst.REQUEST_URL + "getTime";

		StringRequest stringRequest = new StringRequest(url,
				new Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						// TODO Auto-generated method stub
						serverTime = arg0.toString().replace("\"", "");
						serverTime = serverTime.substring(11);

						// System.out.println(nowTime);

						String stime = null;

						int nowHour = Integer.parseInt(serverTime.substring(0,
								2));
						String start = null;
						if (nowHour % 2 != 0) {
							start = Integer.toString(nowHour - 1);
						} else {
							start = Integer.toString(nowHour);
						}

						// String start = hour;
						String end = Integer.toString(Integer.parseInt(start) + 2);

						// C42,start.length()等于2或小于2.end.leng()等于2或小于2
						if (start.length() < 2 && end.length() < 2) {
							stime = "0" + start + ":01 - " + "0" + end + ":00";
						} else if (start.length() < 2 && end.length() == 2) {
							stime = "0" + start + ":01 - " + end + ":00";
						} else if (start.length() == 2 && end.length() == 2) {
							stime = start + ":01 - " + end + ":00";
						} else {
							stime = start + ":01 - " + "0" + end + ":00";
						}
						//
						tv_time2.setText("正在进行");
						tv_time3.setText(stime);
						// rlayout_timing.setVisibility(View.INVISIBLE);

						nowTime();
						doTime();
						timer = new Timer(true);
						timer.schedule(task, 1000, 1000);

						switch (start) {
						case "00":
							rbtn_time0.setChecked(true);
							break;
						case "08":
							rbtn_time8.setChecked(true);
							break;
						case "10":
							rbtn_time10.setChecked(true);
							break;
						case "12":
							rbtn_time12.setChecked(true);
							break;
						case "14":
							rbtn_time14.setChecked(true);
							break;
						case "16":
							rbtn_time16.setChecked(true);
							break;
						case "18":
							rbtn_time18.setChecked(true);
							break;
						case "20":
							rbtn_time20.setChecked(true);
							break;
						case "22":
							rbtn_time22.setChecked(true);
							break;

						default:
							break;
						}

						// nav_radiogroup.set

					}

				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}
				});

		mQueue.add(stringRequest);
	}

	/**
	 * 获取现在时间,时、分、秒
	 */
	public void nowTime() {
		hour = Integer.parseInt(serverTime.substring(0, 2));
		minutes = Integer.parseInt(serverTime.substring(3, 5));
		seconds = Integer.parseInt(serverTime.substring(6, 8));
	}

	/**
	 * 处理时间
	 */
	public void doTime() {

		if (minutes1 != 0 && seconds1 != 0) {
			hour1 = time_zone - hour - 1;
		} else {
			hour1 = time_zone - hour;
		}

		minutes1 = 60 - minutes;
		seconds1 = 60 - seconds;

	}

	/**
	 * Timer执行方法
	 */
	TimerTask task = new TimerTask() {
		@SuppressLint("HandlerLeak")
		public void run() {
			seconds++;
			if (seconds == 60) {
				minutes++;
				if (minutes == 60) {
					hour++;
					if (hour == 24) {
						hour = 0;
					}
					minutes = 0;
				}
				seconds = 0;
			}

			if (rlayout_timing.getVisibility() == View.VISIBLE) {
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}
		}
	};

	@SuppressLint("HandlerLeak")
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:

				doTime();
				String s_hour1 = Integer.toString(hour1);
				if (s_hour1.length() < 2) {
					tv_hour.setText("0" + s_hour1);
				} else {
					tv_hour.setText(s_hour1);
				}

				String s_minute1 = Integer.toString(minutes1);
				if (s_minute1.length() < 2) {
					tv_minutes.setText("0" + s_minute1);
				} else {
					tv_minutes.setText(s_minute1);
				}

				String s_second1 = Integer.toString(seconds1);
				if (s_second1.length() < 2) {
					tv_seconds.setText("0" + s_second1);
				} else {
					tv_seconds.setText(s_second1);
				}

				break;
			}

			super.handleMessage(msg);
		}
	};

	@SuppressLint("HandlerLeak")
	private void spandTimeMethod() {
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	Handler handler1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
			UIHelper.hideDialogForLoading();
			mScrollView.setVisibility(View.VISIBLE);
		}
	};
}
